package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.servlet.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// RESTful标准控制器
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean result = bookService.save(book);
        Integer code = result ? Code.SAVE_OK : Code.SAVE_ERR;
        String message = result ? "保存成功" : "保存失败";

        return new Result(code, result, message);
    }

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        if (id <= 0) {
            //业务异常: 用户造成的
            throw new BusinessException(Code.BUSINESS_ERR, "id不能小于0");
        }
        Book book = null;
        try {
            //数据库可能有问题,抛出异常
            book = bookService.getById(id);

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_ERR, "当前访问人数较多,请稍后访问");
        }

        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String message = book != null ? "查询成功" : "查询失败";
        return new Result(code, book, message);
    }

    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }
}